﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Utils.Common
{
  public class HttpHelper
    {

        ///// <summary>  
        ///// HttpClient实现Post请求   
        ///// </summary>  
        //public static T DoPost<T>(string postUrl, string josnData ,string  appkey =null,string signToken = null)
        //{

        //    //设置HttpClientHandler的AutomaticDecompression  
        //    var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip , UseCookies =false};
        //    //创建HttpClient（注意传入HttpClientHandler）  
        //    using (var httpClient = new HttpClient(handler))
        //    {

        //            var httpContent = new StringContent (josnData);
        //            httpContent.Headers.ContentType=new System.Net.Http.Headers.MediaTypeHeaderValue("application/json") ;
        //            httpContent.Headers.Add("Appkey", appkey);
        //            httpContent.Headers.Add("SignToken", signToken);
        //            HttpResponseMessage response = httpClient.PostAsync(postUrl, httpContent).Result;
        //            if (response.IsSuccessStatusCode)
        //            {
        //                Task<string> t = response.Content.ReadAsStringAsync();
        //                return JsonConvert.DeserializeObject<T>(t.Result);
        //            }
        //            else
        //            {
        //                throw new Exception(response.ReasonPhrase);
        //            }

        //    }

        //}
        ///// <summary>  
        ///// HttpClient实现Post请求   
        ///// </summary>  
        //public static T DoPost<T>(string postUrl, Dictionary<string,string> keyValuePairs, string appkey = null, string signToken = null)
        //{

        //  return   DoPost<T>(postUrl,JsonConvert.SerializeObject(keyValuePairs), appkey, signToken);
        //}




        ///// <summary>  
        ///// HttpClient实现Get请求 
        ///// </summary>  
        //public static   T DoGet<T>(string url, string queryStr, string appkey = null, string signToken = null)
        //{

        //    //创建HttpClient（注意传入HttpClientHandler）  
        //    var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };

        //    using (var httpClient = new HttpClient(handler))
        //    {
        //        var httpContent = new StringContent(queryStr);
        //        httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
        //        httpClient.DefaultRequestHeaders.Add("Appkey", appkey);
        //        httpClient.DefaultRequestHeaders.Add("SignToken", signToken);
        //        HttpResponseMessage response = httpClient.GetAsync(url+"?"+ queryStr).Result;
        //        if (response.IsSuccessStatusCode)
        //        {
        //            Task<string> t = response.Content.ReadAsStringAsync();
        //            return JsonConvert.DeserializeObject<T>(t.Result);
        //        }
        //        else
        //        {
        //            throw new Exception(response.ReasonPhrase);
        //        }


        //    }
        //}

        /// <summary>  
        /// HttpClient实现Post请求   
        /// </summary>  
        public static T DoPostGZip<T>(string postUrl, string josnData, string appkey, string signToken)
        {

            //设置HttpClientHandler的AutomaticDecompression  
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip, UseCookies = false };
            //创建HttpClient（注意传入HttpClientHandler）  
            using (var httpClient = new HttpClient(handler))
            {

                Stream stream = GZipCompress(josnData);
                var httpContent = new StreamContent(stream);
                httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                httpContent.Headers.Add("Appkey", appkey);
                httpContent.Headers.Add("SignToken", signToken);
                HttpResponseMessage response = httpClient.PostAsync(postUrl, httpContent).Result;
                if (response.IsSuccessStatusCode)
                {
                    Task<string> t = response.Content.ReadAsStringAsync();
                    return JsonConvert.DeserializeObject<T>(t.Result);
                }
                else
                {
                    throw new Exception(response.ReasonPhrase);
                }
            }
        }


        ///// <summary>  
        ///// HttpClient实现Put请求(异步)  
        ///// </summary>  
        //static async void dooPut()
        //{
        //    var userId = 1;
        //    string url = "http://localhost:52824/api/register?userid=" + userId;

        //    //设置HttpClientHandler的AutomaticDecompression  
        //    var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
        //    //创建HttpClient（注意传入HttpClientHandler）  
        //    using (var http = new HttpClient(handler))
        //    {
        //        //使用FormUrlEncodedContent做HttpContent  
        //        var content = new FormUrlEncodedContent(new Dictionary<string, string>()
        //{
        //   {"Name","修改zzl"},
        //   {"Info", "Put修改动作"}//键名必须为空  
        //});

        //        //await异步等待回应  

        //        var response = await http.PutAsync(url, content);
        //        //确保HTTP成功状态值  
        //        response.EnsureSuccessStatusCode();
        //        //await异步读取最后的JSON（注意此时gzip已经被自动解压缩了，因为上面的AutomaticDecompression = DecompressionMethods.GZip）  
        //        Console.WriteLine(await response.Content.ReadAsStringAsync());
        //    }
        //}



        ///<summary>
        /// GZipStream压缩字符串
        /// </summary>
        public static Stream GZipCompress(string str)
        {
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
            MemoryStream msReturn;
            using (MemoryStream msTemp = new MemoryStream())
            {
                using (GZipStream gz = new GZipStream(msTemp, CompressionMode.Compress, true))
                {
                    gz.Write(buffer, 0, buffer.Length);
                    gz.Close();
                    msReturn = new MemoryStream(msTemp.GetBuffer(), 0, (int)msTemp.Length);
                }
            }
            return msReturn;
        }


        ///<summary>
        /// GZipStream解压字符串
        /// </summary>
        public static string GZipDecompress(Stream stream)
        {
            byte[] buffer = new byte[100];
            int length = 0;

            using (GZipStream gz = new GZipStream(stream, CompressionMode.Decompress))
            {
                using (MemoryStream msTemp = new MemoryStream())
                {
                    while ((length = gz.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        msTemp.Write(buffer, 0, length);
                    }
                    return System.Text.Encoding.UTF8.GetString(msTemp.ToArray());
                }
            }
        }

        ///// <summary>
        ///// Post请求
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="url"></param>
        ///// <param name="data"></param>
        ///// <param name="staffId"></param>
        ///// <returns></returns>
        //public static T Post<T>(string url, Dictionary<string, string> keyValuePairs, string appkey=null, string signToken = null)
        //{
        //    string data = JsonConvert.SerializeObject(keyValuePairs);
        //    byte[] bytes = Encoding.UTF8.GetBytes(data);
        //    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);


        //    //加入头信息
        //    request.Headers.Add("Appkey", appkey); //发起请求时的时间戳（单位：毫秒）
        //    request.Headers.Add("SignToken", signToken); //当前请求内容的数字签名

        //    //写数据
        //    request.Method = "POST";
        //    request.ContentLength = bytes.Length;
        //    request.ContentType = "application/json";
        //    Stream reqstream = request.GetRequestStream();
        //    reqstream.Write(bytes, 0, bytes.Length);

        //    //读数据
        //    request.Timeout = 300000;
        //    request.Headers.Set("Pragma", "no-cache");
        //    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        //    Stream streamReceive = response.GetResponseStream();
        //    StreamReader streamReader = new StreamReader(streamReceive, Encoding.UTF8);
        //    string strResult = streamReader.ReadToEnd();

        //    //关闭流
        //    reqstream.Close();
        //    streamReader.Close();
        //    streamReceive.Close();
        //    request.Abort();
        //    response.Close();

        //    return JsonConvert.DeserializeObject<T>(strResult);

        //}

        /// <summary>
        /// Post请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <param name="staffId"></param>
        /// <returns></returns>
        public static T Post<T>(string url, object obj, string appkey = null, string signToken = null)
        {

            string data = JsonConvert.SerializeObject(obj);
            byte[] bytes = Encoding.UTF8.GetBytes(data);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);


            //加入头信息
            request.Headers.Add("Appkey", appkey); //发起请求时的时间戳（单位：毫秒）
            request.Headers.Add("SignToken", signToken); //当前请求内容的数字签名

            //写数据
            request.Method = "POST";
            request.ContentLength = bytes.Length;
            request.ContentType = "application/json";
            Stream reqstream = request.GetRequestStream();
            reqstream.Write(bytes, 0, bytes.Length);

            //读数据
            request.Timeout = 300000;
            request.Headers.Set("Pragma", "no-cache");
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream streamReceive = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(streamReceive, Encoding.UTF8);
            string strResult = streamReader.ReadToEnd();

            //关闭流
            reqstream.Close();
            streamReader.Close();
            streamReceive.Close();
            request.Abort();
            response.Close();

            return JsonConvert.DeserializeObject<T>(strResult);
        }
            /// <summary>
            /// Get请求
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="webApi"></param>
            /// <param name="queryStr"></param>
            /// <param name="staffId"></param>
            /// <returns></returns>
         public static T Get<T>(string webApi, Dictionary<string,string>  keyValuePairs ,string appkey, string signToken)
        {

            
            string queryStr= GetQueryString(keyValuePairs);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webApi + queryStr);
            request.Headers.Add("Appkey", appkey); //发起请求时的时间戳（单位：毫秒）
            request.Headers.Add("SignToken", signToken); //当前请求内容的数字签名
            request.Method = "GET";
            request.ContentType = "application/json";
            request.Timeout = 90000;
            request.Headers.Set("Pragma", "no-cache");
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream streamReceive = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(streamReceive, Encoding.UTF8);
            string strResult = streamReader.ReadToEnd();

            streamReader.Close();
            streamReceive.Close();
            request.Abort();
            response.Close();

            return JsonConvert.DeserializeObject<T>(strResult);
        }


        

        /// <summary>
        /// 拼接get参数
        /// </summary>
        /// <param name="parames"></param>
        /// <returns></returns>
        public static string GetQueryString(Dictionary<string, string> parames)
        {
            if (parames == null || parames.Count == 0)
                return "";

            IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parames);
            IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();
            StringBuilder queryStr = new StringBuilder("?"); //url参数
            while (dem.MoveNext())
            {
                string key = dem.Current.Key;
                string value = dem.Current.Value;
                if (!string.IsNullOrEmpty(key))
                {
                    queryStr.Append(key).Append("=").Append(value).Append("&");
                }
            }

            return queryStr.ToString().Trim('&');
        }

    }
}
